package com.lfc.myframe

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.flyco.animation.BounceEnter.BounceEnter
import com.flyco.dialog.listener.OnBtnClickL
import com.flyco.dialog.widget.MaterialDialog
import com.lfc.myframe.share.Const.CAMERA_PERMISSIONS
import com.lfc.myframe.share.Const.CAMERA_REQUEST_CODE
import com.lfc.myframe.share.Const.Data_FileDirPath
import com.lfc.myframe.share.Const.GPS_PERMISSIONS
import com.lfc.myframe.share.Const.GPS_REQUEST_CODE
import com.lfc.myframe.utils.*
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.mdchina.juhai.utils.ToastUtils
import com.tamsiree.rxkit.TLog
import kotlinx.android.synthetic.main.activity_test.*
import kotlinx.coroutines.*
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions
import java.io.File
import java.util.ArrayList


/**
 * 测试 Activity
 */
class TestA : AppCompatActivity(), EasyPermissions.PermissionCallbacks {

    companion object {


        fun EnterThis(context: Context, string: String = "", int: Int = 0) {
            var intent = Intent(context, TestA().javaClass)
            intent.putExtra("strInfo", string)
            intent.putExtra("Type", int)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        //initMVP()
        initView()
        initData()
        getData()
    }

    private fun initView() {
        btn_gettime.setOnClickListener {
            NtpClient.getInstance().getNTPAsync()

        }
        tv_info.setOnClickListener {
            goCamera(this, Data_FileDirPath, 1)
        }
        btn_dialog.setOnClickListener {
            LoadingUtil.showLoading(this, "嘿嘿 嘿嘿")
//            LoadingUtil.showLoading(this, "嘿嘿")

        }
        btn_camera.setOnClickListener {
            CameraUtils.OpenCameraMore(
                this,
                0,
                0,
                9,
                object : OnResultCallbackListener<LocalMedia> {

                    override fun onCancel() {
                    }


                    override fun onResult(result: MutableList<LocalMedia>?) {
                        TLog.d(result.toString())
                    }
                })
        }
        btn_XC.setOnClickListener {
            CoroutineDemo()
        }
        btn_permission.setOnClickListener {
//            cameraTask()
            GpsTask()
        }
        tv2.setText("暗黑？" + LUtils.isDarkTheme(this))
    }

    /**
     * 协程测试
     */
    private fun CoroutineDemo() {
        GlobalScope.launch {
            TLog.d("CoroutineDemo")
//            Test()
//            顺序
            val value1 = request1("KotlinCoroutine")
//            并发
            val value2 = async { request2(value1) }
            val value3 = async { request3(value1) }

            TLog.d(
                "CoroutineDemo end " +
                        "value1:$value1 " +
                        "value2:${value2.await()} " +
                        "value3:${value3.await()}  "
            )
        }

    }

    suspend fun Test() {
        withContext(Dispatchers.IO) {
            TLog.d("CoroutineDemo Testing")
        }
    }

    suspend fun request1(string: String): String {
        var str = string + " 1"
        return str
    }

    suspend fun request2(string: String): String {
        var str = string + " 2"
        return str
    }

    suspend fun request3(string: String): String {
        var str = string + " 3"
        return str
    }

    private fun initData() {
//        GlobalScope.launch {
//            delay(1000L)
//        }
    }

    private fun goCamera(
        activity: Activity,
        filePath: String,
        requestCode: Int
    ) {
        val intent = Intent()
        val imagePath = File(filePath)
        val imageUri: Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(
                activity,
                this.packageName + ".fileprovider",
                imagePath
            )
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        } else {
            imageUri = Uri.fromFile(imagePath)
        }
        intent.action = MediaStore.ACTION_IMAGE_CAPTURE
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        activity.startActivityForResult(intent, requestCode)
    }

    private fun getData() {

    }

    /**
     * 这个回调中  可能还是未同意
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
//        ToastUtils.showToask(this, "可！")

    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
//        ToastUtils.showToask(this, "拒绝！提示去设置一下！")
        val materialDialog = MaterialDialog(this)
        materialDialog.content("需要授予权限才能正常使用应用，是否去设置？")
            .title(baseContext.getString(R.string.DialogTitle))
            .btnText(
                baseContext.getString(R.string.ignoreNote),
                baseContext.getString(R.string.sure)
            )
            .btnTextColor(
                baseContext.resources.getColor(R.color.maintxt),
                baseContext.resources.getColor(R.color.maintxt)
            ).showAnim(BounceEnter())
            .show()
        materialDialog.setOnBtnClickL(
            OnBtnClickL {
                materialDialog.dismiss()
            }, OnBtnClickL //right btn click listener
            {
                materialDialog.dismiss()
                // 打开权限设置页
                MAFWUtils.toSelfSetting(this)

            })

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    @AfterPermissionGranted(CAMERA_REQUEST_CODE)
    fun cameraTask() {

        if (EasyPermissions.hasPermissions(this, *CAMERA_PERMISSIONS)) {
            ToastUtils.showToask(this, "拍照呦！！")

        } else {
            EasyPermissions.requestPermissions(
                this,
                "应用需要访问相机权限!",
                CAMERA_REQUEST_CODE,
                *CAMERA_PERMISSIONS
            )
        }

    }

    @AfterPermissionGranted(GPS_REQUEST_CODE)
    fun GpsTask() {

        if (EasyPermissions.hasPermissions(this, *GPS_PERMISSIONS)) {
            ToastUtils.showToask(this, "拍照呦！！")

        } else {
            EasyPermissions.requestPermissions(
                this,
                "应用需要访问相机权限!",
                GPS_REQUEST_CODE,
                *GPS_PERMISSIONS
            )
        }

    }
}
